using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using MCromwell.StaffIntranet.Core;
using nhibernate = NHibernate;
using NHibernate.Criterion;
using NHibernate;

namespace MCromwell.StaffIntranet.Data.NHibernate
{
    public class NHibernateAdministrationRepository : IAdministrationRepository
    {
     
        public Administrator FindAdministratorUsing(string Username)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            return session.CreateCriteria(typeof(Administrator))
                            .Add(Expression.Eq("Credentials.Username", Username))
                            .UniqueResult<Administrator>();
        }

        public LoginSession StartSessionFor(Administrator administrator)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            
            LoginSession loginSession = new LoginSession();
            loginSession.Administrator = administrator;
            loginSession.StartedAt = DateTime.Now;
            loginSession.LastActivity = DateTime.Now;
            session.Save(loginSession);

            NHibernateSessionManager.Instance.CommitTransaction();

            return loginSession;
        }
        
        public LoginSession FindLoginSessionBy(Guid SessionId)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            return session.CreateCriteria(typeof(LoginSession))
                            .Add(Expression.Eq("Id", SessionId))
                            .UniqueResult<LoginSession>();
        }
        
        public void Update(LoginSession Session)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();

            try
            {
                NHibernateSessionManager.Instance.BeginTransaction();
                session.Update(Session);
                NHibernateSessionManager.Instance.CommitTransaction();
            }
            catch (Exception)
            {
                NHibernateSessionManager.Instance.RollbackTransaction();
                throw;
            }
                                    
        }

        public void Delete(LoginSession Session)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            try
            {
                session.Delete(Session);
                NHibernateSessionManager.Instance.CommitTransaction();
            }
            catch (Exception)
            {
                NHibernateSessionManager.Instance.RollbackTransaction();
                throw;
            }
            
            
        }
    }
}
